<template>
  <view class="container">
    <view class="form-section">
      <!-- 用户昵称 -->
      <view class="form-item">
        <view class="label">用户昵称</view>
        <input 
          class="input" 
          v-model="user.nickName" 
          placeholder="请输入昵称"
          placeholder-style="color: #999;"
        />
      </view>
      
      <!-- 手机号码 -->
      <view class="form-item">
        <view class="label">手机号码</view>
        <input 
          class="input" 
          v-model="user.phonenumber" 
          placeholder="请输入手机号码"
          type="number"
          maxlength="11"
          placeholder-style="color: #999;"
        />
      </view>
      
      <!-- 邮箱 -->
      <view class="form-item">
        <view class="label">邮箱</view>
        <input 
          class="input" 
          v-model="user.email" 
          placeholder="请输入邮箱"
          type="text"
          placeholder-style="color: #999;"
        />
      </view>
      
      <!-- 性别 -->
      <view class="form-item">
        <view class="label">性别</view>
        <radio-group @change="onSexChange" class="radio-group">
          <label class="radio-item">
            <radio :value="0" :checked="user.sex === '0' || user.sex === 0" color="#3c96f3" />
            <text class="radio-text">男</text>
          </label>
          <label class="radio-item">
            <radio :value="1" :checked="user.sex === '1' || user.sex === 1" color="#3c96f3" />
            <text class="radio-text">女</text>
          </label>
        </radio-group>
      </view>
      
      <!-- 提交按钮 -->
      <view class="button-section">
        <button type="primary" @click="submit" class="submit-btn">提交</button>
      </view>
    </view>
  </view>
</template>

<script>
  import { getUserProfile, updateUserProfile } from "@/api/system/user"

  export default {
    data() {
      return {
        user: {
          nickName: "",
          phonenumber: "",
          email: "",
          sex: "0"
        }
      }
    },
    onLoad() {
      this.getUser()
    },
    methods: {
      getUser() {
        getUserProfile().then(response => {
          if (response && response.data) {
            this.user = response.data
            // 确保性别字段是字符串
            if (this.user.sex !== undefined && this.user.sex !== null) {
              this.user.sex = String(this.user.sex)
            }
          }
        }).catch(err => {
          console.error('获取用户信息失败:', err)
          uni.showToast({
            title: '获取用户信息失败',
            icon: 'none'
          })
        })
      },
      onSexChange(e) {
        this.user.sex = String(e.detail.value)
      },
      validateForm() {
        // 验证昵称
        if (!this.user.nickName || this.user.nickName.trim() === '') {
          uni.showToast({
            title: '请输入用户昵称',
            icon: 'none'
          })
          return false
        }
        
        // 验证手机号
        if (!this.user.phonenumber || this.user.phonenumber.trim() === '') {
          uni.showToast({
            title: '请输入手机号码',
            icon: 'none'
          })
          return false
        }
        
        const phoneReg = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/
        if (!phoneReg.test(this.user.phonenumber)) {
          uni.showToast({
            title: '请输入正确的手机号码',
            icon: 'none'
          })
          return false
        }
        
        // 验证邮箱
        if (!this.user.email || this.user.email.trim() === '') {
          uni.showToast({
            title: '请输入邮箱地址',
            icon: 'none'
          })
          return false
        }
        
        const emailReg = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/
        if (!emailReg.test(this.user.email)) {
          uni.showToast({
            title: '请输入正确的邮箱地址',
            icon: 'none'
          })
          return false
        }
        
        return true
      },
      submit() {
        if (!this.validateForm()) {
          return
        }
        
        // 显示加载提示
        uni.showLoading({
          title: '提交中...'
        })
        
        updateUserProfile(this.user).then(response => {
          uni.hideLoading()
          uni.showToast({
            title: '修改成功',
            icon: 'success'
          })
          
          // 更新成功后，刷新 store 中的用户信息
          if (this.$store && this.$store.dispatch) {
            this.$store.dispatch('GetInfo').then(() => {
              // 返回上一页，让用户看到更新后的名字
              setTimeout(() => {
                uni.navigateBack()
              }, 1500)
            }).catch(err => {
              console.error('刷新用户信息失败:', err)
              // 即使刷新失败也返回上一页
              setTimeout(() => {
                uni.navigateBack()
              }, 1500)
            })
          } else {
            // 如果 store 不可用，直接返回
            setTimeout(() => {
              uni.navigateBack()
            }, 1500)
          }
        }).catch(err => {
          uni.hideLoading()
          console.error('修改失败:', err)
          uni.showToast({
            title: err.message || '修改失败，请重试',
            icon: 'none',
            duration: 2000
          })
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  page {
    background-color: #f5f5f5;
  }

  .container {
    min-height: 100vh;
  }

  .form-section {
    background-color: #fff;
    margin: 10px;
    border-radius: 8px;
    padding: 0;
    overflow: hidden;
  }

  .form-item {
    display: flex;
    align-items: center;
    padding: 15px;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
  }

  .label {
    width: 90px;
    font-size: 15px;
    color: #333;
    flex-shrink: 0;
  }

  .input {
    flex: 1;
    font-size: 15px;
    color: #333;
    text-align: right;
  }

  .radio-group {
    flex: 1;
    display: flex;
    justify-content: flex-end;
  }

  .radio-item {
    display: flex;
    align-items: center;
    margin-left: 20px;
  }

  .radio-text {
    margin-left: 5px;
    font-size: 15px;
    color: #333;
  }

  .button-section {
    padding: 20px 15px;
  }

  .submit-btn {
    width: 100%;
    background-color: #3c96f3;
    color: #fff;
    border-radius: 8px;
    height: 45px;
    line-height: 45px;
    font-size: 16px;
    border: none;
  }
  
  button::after {
    border: none;
  }
</style>
